// CSE 142, Winter 2008, Marty Stepp // // This program computes prime numbers. This is an updated version of a // program we wrote previously, updated to use an isPrime method that // returns a boolean result. public class Primes2 { public static void main(String[] args) { printPrimes(50); printPrimes(1000); printPrimes(1); } public static void printPrimes(int max) { System.out.print("["); if (max >= 2) { System.out.print(2); for (int i = 3; i <= max; i++) { // new code if (isPrime(i)) { System.out.print(", " + i); } } } System.out.println("]"); } // new code // Returns true if n is prime, and false if not. public static boolean isPrime(int n) { if (countFactors(n) == 2) { return true; } else { return false; } } // Returns the number of factors of the given integer. // Assumes that a non-negative number is passed. public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { // i is a factor of the number count++; } } return count; } }